<?php
/*	Request validation class
 * 	used to validate incoming values automatically
 * 	Specially for Open-CMF core
 */
 
class OCRequest {
	private static $init=false;
	private static $st_text=array();
	private static $st_number=array();
	private static $st_sql=array();
	private static $st_sql_name=array();
	
	//Constructor
	public function __construct() {
		if(!self::$init) self::init();
		$this->text = self::$st_text;
		$this->number = self::$st_number;
		$this->sql = self::$st_sql;
		$this->sql_name = self::$st_sql_name;
	}
	
	//Initialize request vars
	public static function init() {
		if(!self::$init) {
			$request=array();
			self::$init=true;
			foreach($_GET as $index=>$value) self::set($index,$value);
			unset($_GET);
			unset($_POST);
		}
	}
	
	//Set data to array
	private static function set($index,$value) {
		self::$st_text[$index]=$value;
		if(strlen($value) and @is_numeric(substr($value,0,1))) self::$st_number[$index]=(int)$value;
		self::$st_sql[$index]='"'.self::escape($value).'"';
		self::$st_sql_name[$index]='`'.str_replace(array(' ', '/t'),'_',self::escape($value)).'`';
	}
	
	//String to use in sql query as value
	public function sql($index) {
		if(!self::$init) self::init();
		if(isset(self::$st_sql[$index])) return self::$st_sql[$index];
		else return false;
	}
	
	//String to use in sql as query name
	public function sql_name($index) {
		if(!self::$init) self::init();
		if(isset(self::$st_sql_row[$index])) return self::$st_sql_row[$index];
		else return false;
	}
	
	//Plain text value
	public function text($index) {
		if(!self::$init) self::init();
		if(isset(self::$st_text[$index])) return self::$st_text[$index];
		else return false;
	}
	
	//Integer number value
	public function number($index) {
		if(!self::$init) self::init();
		if(isset(self::$st_number[$index])) return self::$st_number[$index];
		else return false;
	}
	
	//mysql_real_escape_string() no connection alternative
	private static function escape($value) {
		$return = '';
		for($i = 0; $i < strlen($value); ++$i) {
			$char = $value[$i];
			$ord = ord($char);
			if($char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126)
				$return .= $char;
			else
				$return .= '\\x' . dechex($ord);
		}
		return $return;
	}
} 
?>
